
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * manualCustomerGUI.java
 *
 * Created on 2011-okt-12, 10:27:30
 */

/**
 *
 * @author pase0900
 */
public class manualCustomerGUI extends javax.swing.JFrame {

    DocumentBuilderFactory docBuildFact;
    DocumentBuilder docBuild;
    TransformerFactory transFactory;


    /** Creates new form manualCustomerGUI */
    public manualCustomerGUI() {
        try {
            initComponents();
            docBuildFact = DocumentBuilderFactory.newInstance();
            docBuild = docBuildFact.newDocumentBuilder();
            transFactory = TransformerFactory.newInstance();
        } catch (Throwable t) {
            t.printStackTrace(System.out);
            System.exit(-1);
        }
        refreshList();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        refreshButton = new javax.swing.JButton();
        buyButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        itemTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        refreshButton.setText("Refresh");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        buyButton.setText("Buy Item");
        buyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buyButtonActionPerformed(evt);
            }
        });

        itemTable.setAutoCreateRowSorter(true);
        itemTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Item", "ID", "Price", "Quantity"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(itemTable);

        jScrollPane2.setViewportView(jScrollPane1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 538, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(refreshButton)
                        .addGap(31, 31, 31)
                        .addComponent(buyButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(refreshButton)
                    .addComponent(buyButton))
                .addGap(62, 62, 62))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed

      refreshList();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void buyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buyButtonActionPerformed
        int i = itemTable.getSelectedRow();
        Object idNumber = itemTable.getValueAt(i,1);
        Integer id = new Integer(idNumber.toString());
        int  aa = JOptionPane.showConfirmDialog(rootPane, "Are you sure you want to purchase this item?");
        if(aa==0){
        orderItem(id);
        }else{          
        }
    }//GEN-LAST:event_buyButtonActionPerformed

    private List<Item> parseItems(String xml) {
        ArrayList<Item> items = new ArrayList<Item>();
        try {
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            Document doc = docBuild.parse(is);

            Element root = doc.getDocumentElement();
            NodeList nl = root.getElementsByTagName("item");
            if(nl!=null && nl.getLength()>0) {
                for(int i=0;i<nl.getLength();i++){
                    Element currentNode = (Element)nl.item(i);
                    int id = Integer.parseInt(currentNode.getElementsByTagName("id").item(0).getTextContent());
                    int price = Integer.parseInt(currentNode.getElementsByTagName("price").item(0).getTextContent());
                    int quantity = Integer.parseInt(currentNode.getElementsByTagName("quantity").item(0).getTextContent());
                    String name = currentNode.getElementsByTagName("name").item(0).getTextContent();

                    items.add(new Item(id, price, quantity, name));
                }
            }

        } catch(Exception e) {
            System.err.println("error");
        }
        return items;
    }

    public void refreshList(){

    String xml = getAllItems();
    List<Item> items = parseItems(xml);
    for(int i=0; i<items.size(); i++){

        itemTable.setValueAt(parseItems(xml).get(i).getName(),i,0);
        itemTable.setValueAt(parseItems(xml).get(i).getId(),i,1);
        itemTable.setValueAt(parseItems(xml).get(i).getPrice(),i,2);
        itemTable.setValueAt(parseItems(xml).get(i).getQuantity(),i,3);
    }
    }

        private void orderItem(int _id) {
        Document doc = docBuild.newDocument();

        Element root = doc.createElement("order");
        doc.appendChild(root);

        Element id = doc.createElement("id");
        root.appendChild(id);
        id.appendChild(doc.createTextNode(""+_id));

        Element quantity = doc.createElement("quantity");
        root.appendChild(quantity);
        quantity.appendChild(doc.createTextNode("1"));

        String result = buyItem(xmlToString(doc));
    }
            private String xmlToString(Document doc) {
        try {
            StringWriter buffer = new StringWriter();
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            transformer.transform(new DOMSource(doc), new StreamResult(buffer));
            return buffer.toString();
        } catch (Throwable t) {
            return "ERROR: " + t.getMessage();
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new manualCustomerGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buyButton;
    private javax.swing.JTable itemTable;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton refreshButton;
    // End of variables declaration//GEN-END:variables

    private static String getAllItems() {
        warehouse.WarehouseService service = new warehouse.WarehouseService();
        warehouse.Warehouse port = service.getWarehousePort();
        return port.getAllItems();
    }

    private static String buyItem(java.lang.String order) {
        warehouse.WarehouseService service = new warehouse.WarehouseService();
        warehouse.Warehouse port = service.getWarehousePort();
        return port.buyItem(order);
    }

}
